package cn.yunhe.servlet;

import cn.yunhe.entity.Admin;
import cn.yunhe.service.AdminService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //得到页面提交的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //将用户名和密码传给AdminService，根据返回的结果决定是跳转到主页还是不动
        AdminService adminService = new AdminService();
        Admin admin = adminService.loginAdmin(new Admin(username, password));
        if (admin != null) {
            request.getSession().setAttribute("admin", admin);
            request.getRequestDispatcher("main.html").forward(request, response);
        } else {
            response.sendRedirect("login.html");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
